﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data.OleDb;
using System.Data;
using SmartSpace.Core;
using System.Threading;
using System.IO;
using SmartSpace.Packaging;

namespace SsTool.Install
{
    /// <summary>
    /// Interaction logic for ImportOrgFromExcel.xaml
    /// </summary>
    public partial class ImportOrgFromExcel : Page
    {
        private string _filePath;

        public ImportOrgFromExcel()
        {
            InitializeComponent();
        }

        private void _ctlBtnBroswer_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "excel(*.xlsx)|*.xlsx";
            dlg.Multiselect = false;
            if (dlg.ShowDialog() == true)
            {
                _ctlBtnBroswer.Content = dlg.FileName;

                _filePath = dlg.FileName;

                ExcelUtil util = new ExcelUtil(_filePath);
                _ctlListSheets.ItemsSource = util.GetSheets();
                util.Close();
            }
        }

        private void _ctlListSheets_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string sheetName = e.AddedItems[0].ToString();

            ExcelUtil util = new ExcelUtil(_filePath);
            DataTable table = util.GetData(sheetName, 20);
            util.Close();

            List<string> columns = new List<string>();
            foreach (DataColumn item in table.Columns)
            {
                columns.Add(item.ColumnName);
            }

            _ctlListParent.ItemsSource = columns;
            _ctlListCode.ItemsSource = columns;
            _ctlListCaption.ItemsSource = columns;
            _ctlListOrderIndex.ItemsSource = columns;
        }

        private void _ctlBtnImport_Click(object sender, RoutedEventArgs e)
        {
            string parentCode = _ctlEditParentCode.Text;

            string parentColumn = _ctlListParent.SelectedItem.ToString();
            string codeColumn = _ctlListCode.SelectedItem.ToString();
            string captionColumn = _ctlListCaption.SelectedItem.ToString();
            string orderIndexColumn = _ctlListOrderIndex.SelectedItem.ToString();

            string sheetName = _ctlListSheets.SelectedItem.ToString();


            Thread thread = new Thread(new ParameterizedThreadStart(Importing));

            this.IsEnabled = false;
            this._ctlOutput.Text = string.Empty;
            thread.Start(new string[] { parentCode, parentColumn, codeColumn, captionColumn, orderIndexColumn, sheetName });
        }

        private void Importing(object p)
        {
            string[] args = (string[])p;
            ExcelUtil util = new ExcelUtil(_filePath);
            DataTable table = util.GetData(args[5]);
            util.Close();

            ICoreService coreService = App.Get<ICoreService>();

            string rootCode = args[0];
            string parentColumn = args[1];
            string codeColumn = args[2];
            string captionColumn = args[3];
            string orderIndexColumn = args[4];

            DataRow[] rootRows = table.Select(string.Format("{0}='{1}'", codeColumn, rootCode));
            if (rootRows.Length != 1)
            {
                MessageBox.Show(string.Format("没有发现编号{0}为的结点!", rootCode));
                Dispatcher.Invoke(new Action(Failure));
                return;
            }
            else
            {
                Org org = new Org();
                org.Id = Guid.NewGuid();
                org.Caption = Convert.ToString(rootRows[0][captionColumn]).Trim();
                org.Code = Convert.ToString(rootRows[0][codeColumn]).Trim();
                try
                {
                    org.SortIndex = Convert.ToInt32(rootRows[0][orderIndexColumn]);
                }
                catch
                {
                }

                if (coreService.SaveOrg(org))
                {
                    Dispatcher.Invoke(new Action<Org>(Render), org);
                    ImportChildren(table, parentColumn, codeColumn, captionColumn, orderIndexColumn, org);

                    Dispatcher.Invoke(new Action(Finish));
                }
                else
                {
                    Dispatcher.Invoke(new Action(Failure));
                }
            }
        }

        private void ImportChildren(
            DataTable table, 
            string parentColumn,
            string codeColumn,
            string captionColumn,
            string orderIndexColumn,
            Org org)
        {
            ICoreService coreService = App.Get<ICoreService>();
            DataRow[] rootRows = table.Select(string.Format("{0}='{1}'", parentColumn, org.Code));
            for (int i = 0; i < rootRows.Length; i++)
            {
                DataRow row = rootRows[i];
                string parentCode = Convert.ToString(row[parentColumn]);
                string code = Convert.ToString(row[codeColumn]);
                string caption = Convert.ToString(row[captionColumn]);
                string orderIndex = Convert.ToString(row[orderIndexColumn]);

                if (!string.IsNullOrEmpty(code) && !string.IsNullOrEmpty(caption))
                {
                    Org subOrg = new Org();
                    subOrg.Id = Guid.NewGuid();
                    subOrg.Caption = caption.Trim();
                    subOrg.Code = code.Trim();
                    subOrg.ParentId = org.Id;
                    try
                    {
                        subOrg.SortIndex = Convert.ToInt32(orderIndex);
                    }
                    catch
                    {
                    }

                    if (coreService.SaveOrg(subOrg))
                    {
                        ImportChildren(table, parentColumn, codeColumn, captionColumn, orderIndexColumn, subOrg);
                        Dispatcher.Invoke(new Action<Org>(Render), subOrg);
                    }
                }
            }
        }

        private void Render(Org org)
        {
            _ctlOutput.Text += string.Format("导入{1}({0})成功!{2}", org.Code, org.Caption, Environment.NewLine);
            _ctlOutput.ScrollToEnd();
        }

        private void Finish()
        {
            _ctlOutput.Text += "导入完毕";
            _ctlOutput.ScrollToEnd();

            this.IsEnabled = true;
        }

        private void Failure()
        {
            this.IsEnabled = true;
        }

#region 导出到xml
        private void _ctlBtnExportXml_Click(object sender, RoutedEventArgs e)
        {
            string parentCode = _ctlEditParentCode.Text;

            string parentColumn = _ctlListParent.SelectedItem.ToString();
            string codeColumn = _ctlListCode.SelectedItem.ToString();
            string captionColumn = _ctlListCaption.SelectedItem.ToString();
            string orderIndexColumn = _ctlListOrderIndex.SelectedItem.ToString();

            string sheetName = _ctlListSheets.SelectedItem.ToString();


            Thread thread = new Thread(new ParameterizedThreadStart(ImportingXml));

            this.IsEnabled = false;
            this._ctlOutput.Text = string.Empty;
            thread.Start(new string[] { parentCode, parentColumn, codeColumn, captionColumn, orderIndexColumn, sheetName });
        }

        private void ImportingXml(object p)
        {
            string[] args = (string[])p;
            ExcelUtil util = new ExcelUtil(_filePath);
            DataTable table = util.GetData(args[5]);
            util.Close();

            ICoreService coreService = App.Get<ICoreService>();

            string rootCode = args[0];
            string parentColumn = args[1];
            string codeColumn = args[2];
            string captionColumn = args[3];
            string orderIndexColumn = args[4];

            DataRow[] rootRows = table.Select(string.Format("{0}='{1}'", codeColumn, rootCode));
            if (rootRows.Length != 1)
            {
                MessageBox.Show(string.Format("没有发现编号{0}为的结点!", rootCode));
                Dispatcher.Invoke(new Action(Failure));
                return;
            }
            else
            {
                Org org = new Org();
                org.Id = Guid.NewGuid();
                org.Caption = Convert.ToString(rootRows[0][captionColumn]).Trim();
                org.Code = Convert.ToString(rootRows[0][codeColumn]).Trim();
                org.Children = new List<Org>();
                try
                {
                    org.SortIndex = Convert.ToInt32(rootRows[0][orderIndexColumn]);
                }
                catch
                {
                }

                Dispatcher.Invoke(new Action<Org>(Render), org);
                ImportChildrenXml(table, parentColumn, codeColumn, captionColumn, orderIndexColumn, org);


                FileInfo fi = new FileInfo(_filePath);
                string xmlFileName = fi.Name.Replace(fi.Extension, string.Empty);
                string xmlFilePath = fi.Directory.FullName + "\\" + xmlFileName + "(org).xml";
                List<Org> orgs = new List<Org>();
                orgs.Add(org);
                XOrgUtil.Save(orgs, xmlFilePath);
                Dispatcher.Invoke(new Action<string>(Finish2), xmlFilePath);

            }
        }
     
        private void Finish2(string path)
        {
            _ctlOutput.Text += "导入完成:" + path;
            _ctlOutput.ScrollToEnd();
            this.IsEnabled = true;
        }

        private void ImportChildrenXml(
            DataTable table,
            string parentColumn,
            string codeColumn,
            string captionColumn,
            string orderIndexColumn,
            Org org)
        {
            ICoreService coreService = App.Get<ICoreService>();
            DataRow[] rootRows = table.Select(string.Format("{0}='{1}'", parentColumn, org.Code));
            for (int i = 0; i < rootRows.Length; i++)
            {
                DataRow row = rootRows[i];
                string parentCode = Convert.ToString(row[parentColumn]);
                string code = Convert.ToString(row[codeColumn]);
                string caption = Convert.ToString(row[captionColumn]);
                string orderIndex = Convert.ToString(row[orderIndexColumn]);

                if (!string.IsNullOrEmpty(code) && !string.IsNullOrEmpty(caption))
                {
                    bool isExist = false;
                    foreach (var item in org.Children)
                    {
                        if (item.Code == code)
                        {
                            isExist = true;
                            break;
                        }
                    }

                    if (!isExist)
                    {
                        Org subOrg = new Org();
                        subOrg.Id = Guid.NewGuid();
                        subOrg.Caption = caption.Trim();
                        subOrg.Code = code.Trim();
                        subOrg.ParentId = org.Id;
                        subOrg.Children = new List<Org>();
                        try
                        {
                            subOrg.SortIndex = Convert.ToInt32(orderIndex);
                        }
                        catch
                        {
                        }

                        org.Children.Add(subOrg);
                        ImportChildrenXml(table, parentColumn, codeColumn, captionColumn, orderIndexColumn, subOrg);
                        Dispatcher.Invoke(new Action<Org>(Render), subOrg);
                    }
                }
            }
        }
#endregion
    }
}
